package com.levi.core;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.levi.core.impl.MethodInvokeImpl;
import com.levi.core.impl.ParamResloverImpl;
import com.levi.core.impl.UrlMappingImpl;
import com.levi.core.impl.ViewResolverImpl;
import com.levi.start.ContextInitListener;

/**
 * 我们所有的请求都进该方法
 * 
 * @author cpp
 * 
 *         这里很好的展现springmvc的中各个处理器的调用流程，以及当用户请求访问url路径到页面的渲染的整个流程
 *
 */
public class CoreServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UrlMapping urlMapping = new UrlMappingImpl();

	private ParamReslover paramResolver = new ParamResloverImpl();

	private MethodInvoke methodInvoke = new MethodInvokeImpl();

	private ViewResolver viewResolver = new ViewResolverImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1 用户请求开始
		// 2 urlMapping
		Method method = urlMapping.mappingUrl(req.getRequestURI(), req.getMethod());
		// 3 将网页上传递过来的参数，转化为我们即将要调用的参数
		Object args[] = paramResolver.resolverParam(req.getParameterMap(), method);
		// 3 完成方法的调用
		// 从ioc容器里里面获取obj
		//
		Class<?> classs = method.getDeclaringClass();
		Object obj = ContextInitListener.iocs.get(classs.getSimpleName());
		Object result = methodInvoke.invoke(obj, method, args);
		// 4 页面渲染
		String template = viewResolver.viewResolver(result);
		PrintWriter writer = resp.getWriter();
		writer.println(template);
		writer.flush();
		writer.close();
		super.service(req, resp);
	}
}
